package org.paybiz.core.service.callback;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.paybiz.constant.PayConstant;
import org.paybiz.model.PayResultDO;
import org.paybiz.util.RequestTools;

/**
 * 支付回调接口定义
 * @author nassir.wen
 * @date 2013-1-8上午9:42:32
 * @company: MSD. 
 * @copyright: Copyright (c) 2013
 */
public abstract class AbstractPayCallback implements PayCallbackService{

    private final Log logger = LogFactory.getLog(getClass());

    /**
     * 支付回调
     * @author nassir.wen
     * @date 2013-1-8上午9:48:18
     * @return
     */
    @Override
    public PayResultDO payCallback(HttpServletRequest request,HttpServletResponse response) {
        if (logger.isInfoEnabled()) {
            logger.info("begin...");
        }
        logger.info("第三方完整回调链接: " + RequestTools.getCompleteRequestUrl(request));
        PayResultDO payResult = verifyResult(request,response);
        logger.info("支付回调结果: " + payResult);
        return payResult;
    }

    /**
     * 发送异步通知结果到第三方
     * @author nassir.wen
     * @date 2013-1-9下午6:15:19
     * @param Response
     * @param result 0 为成功 1为失败
     */
    public void sendAsynResult(HttpServletResponse response, int result) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if (result == PayConstant.RESULT_SUCCESS) {
                logger.info("异步回调成功");
            } else {
                logger.info("异步回调失败");
            }
            out.println(send(result));
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 验证参数结果,模板方法由子类实现
     * @author nassir.wen
     * @date 2013-1-10下午2:51:25
     * @param request
     * @return
     */
    protected abstract PayResultDO verifyResult(HttpServletRequest request,HttpServletResponse response);

    /**
     * 发送通知结果模板方法由子类实现
     * @author nassir.wen
     * @date 2013-1-10下午2:52:53
     * @param result
     */
    protected abstract String send(int result);
}
